package com.pms.controller;

import com.pms.common.PageBean;
import com.pms.pojo.SysUser;
import com.pms.pojo.vo.UserLoginVo;
import com.pms.result.Result;
import com.pms.service.SysUserService;
import com.pms.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody SysUser sysUser) {

        log.info("用户登录，{}", sysUser);

        SysUser login = sysUserService.login(sysUser);

        if (login != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", login.getId());
            claims.put("name", login.getName());
            claims.put("roleType", login.getRoleType());

            String jwt = JwtUtils.generateJwt(claims);

            UserLoginVo userLoginVo = UserLoginVo.builder()
                    .id(login.getId())
                    .name(login.getName())
                    .code(login.getCode())
                    .roleType(login.getRoleType())
                    .deptName(login.getDeptName())
                    .postName(login.getPostName())
                    .status(login.getStatus())
                    .email(login.getEmail())
                    .phone(login.getTelephone())
                    .token(jwt)
                    .build();

            return Result.success(userLoginVo);
        }

        //登录失败
        return Result.error("用户名或密码错误");
    }

    /**
     * 获取当前登录用户的详细信息
     */
    @GetMapping("/info")
    public Result<SysUser> getCurrentUserInfo(HttpServletRequest request) {
        try {
            // 从JWT中获取用户ID
            Long userId = JwtUtils.getCurrentUserId(request);
            if (userId == null) {
                return Result.error("获取用户信息失败：未登录或token已失效");
            }

            log.info("获取用户信息: userId={}", userId);

            // 获取用户详细信息
            SysUser userInfo = sysUserService.getUserDetailInfo(userId);
            if (userInfo != null) {
                // 处理敏感信息
                userInfo.setPassword(null); // 确保不返回密码
                return Result.success(userInfo);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 修改密码
     *
     * @param params 包含旧密码和新密码的Map
     * @return Result
     */
    @PutMapping("/password")
    public Result<String> updatePassword(@RequestBody Map<String, String> params, HttpServletRequest request) {
        log.info("修改密码");

        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");

        // 从JWT中获取当前用户ID，传入request参数
        Long userId = JwtUtils.getCurrentUserId(request);

        if (userId == null) {
            return Result.error("用户未登录或登录已过期");
        }

        if (oldPassword == null || newPassword == null) {
            return Result.error("密码不能为空");
        }

        try {
            sysUserService.updatePassword(userId, oldPassword, newPassword);
            return Result.success("密码修改成功");
        } catch (Exception e) {
            log.error("密码修改失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 新增员工
     *
     * @param sysUser
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody SysUser sysUser) {
        log.info("新增员工：{}", sysUser);
        sysUserService.save(sysUser);
        return Result.success("新增员工成功");
    }

    /**
     * 更新员工
     *
     * @param id      员工ID
     * @param sysUser 员工信息
     * @return
     */
    @PutMapping("/{id}")  // 修改这里，添加前导斜杠
    public Result<String> update(@PathVariable Long id, @RequestBody SysUser sysUser) {
        log.info("更新员工，id：{}，员工信息：{}", id, sysUser);
        sysUser.setId(id);  // 确保设置ID
        sysUserService.update(sysUser);
        return Result.success("更新员工成功");
    }

    /**
     * 删除员工
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> delete(@PathVariable Long id) {
        log.info("删除员工，id：{}", id);
        sysUserService.delete(id);
        return Result.success("删除员工成功");
    }

    /**
     * 根据id查询员工
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<SysUser> getById(@PathVariable Long id) {
        log.info("根据id查询员工：{}", id);
        SysUser sysUser = sysUserService.getById(id);
        return Result.success(sysUser);
    }


    /**
     * 分页条件查询员工列表
     */
    @GetMapping("/page")
    public Result<PageBean<SysUser>> page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String code,
            String name,
            Long deptId,
            Long postId,
            Integer status
    ) {
        log.info("分页查询员工，页码：{}，每页记录数：{}，查询条件：code={}, name={}, deptId={}, postId={}, status={}",
                page, pageSize, code, name, deptId, postId, status);

        PageBean<SysUser> pageResult = sysUserService.page(page, pageSize, code, name, deptId, postId, status);
        return Result.success(pageResult);
    }

    /**
     * 批量获取用户信息
     *
     * @param userIds 用户ID列表，逗号分隔
     * @return 用户信息列表
     */
    @GetMapping("/batch")
    public Result<List<SysUser>> batchGetUsers(@RequestParam String userIds) {
        log.info("批量查询用户信息，userIds：{}", userIds);

        List<Long> idList = Arrays.stream(userIds.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        List<SysUser> users = sysUserService.findByIds(idList);
        return Result.success(users);
    }

    /**
     * 批量删除员工
     */
    @DeleteMapping("/batch")
    public Result<String> batchDelete(@RequestBody List<Long> ids) {
        log.info("批量删除员工，ids：{}", ids);
        sysUserService.batchDelete(ids);
        return Result.success("批量删除员工成功");
    }

    /**
     * 导出员工数据
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        try {
            sysUserService.export(response);
        } catch (Exception e) {
            log.error("导出员工数据失败", e);
        }
    }

    /**
     * 查询所有员工
     *
     * @return
     */
    @GetMapping
    public Result<List> list() {
        log.info("查询所有员工,{}");
        List<SysUser> list = sysUserService.list();
        return Result.success(list);
    }


    /**
     * 更新员工状态
     *
     * @param id
     * @param status
     * @return
     */
    @PutMapping("/status/{id}/{status}")
    public Result<String> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        log.info("更新员工状态，id：{}，status：{}", id, status);
        sysUserService.updateStatus(id, status);
        return Result.success("员工状态更新成功");
    }

}
